package com.itheima.ydd.controller;

import com.itheima.ydd.common.ResultData;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;

    @PostMapping("/upload")
    public ResultData upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + substring;
        String path=basePath+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //将临时文件转存到指定位置
        try {
            file.transferTo(new File(path+"\\"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> data = new HashMap<>();
        data.put("size",file.getSize());
        data.put("mime","image/"+substring.substring(1));
        data.put("name",file.getOriginalFilename());
        data.put("savePath",path+"\\"+fileName);
        return ResultData.ok("成功",data);
    }

    /**
     * 下载
     * @param name
     * @param response
     * @return
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流
            FileInputStream fileInputStream = new FileInputStream(name);
            //输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //响应格式
            response.setContentType("image/jpeg");
            //读->写
         /*   int len=0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }*/
            IOUtils.copy(fileInputStream,outputStream);
            //关流
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
